package com.aiti.ai.tool;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.aiti.ai.dto.ai.SearXNGWebSearchResponse;
import com.aiti.ai.dto.ai.WebSearchResultDto;
import com.aiti.ai.utils.WebSearchUtils;
import dev.langchain4j.agent.tool.P;
import dev.langchain4j.agent.tool.Tool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ description: SearXNGWebSearchTool
 * @ auth fcb
 * @ date 2025-03-19 16:49
 **/
@Component
@Slf4j
public class SearXNGWebSearchTool {

    @Resource
    private WebSearchUtils webSearchUtils;

    @Tool("使用元搜索引擎searXNG 进行搜索互联网网页，输入应为企业名称，输出将返回搜索结果的详细信息，包括网页摘要、网页内容")
    public String searXNGWebSearchTool(@P("企业名称")String enterpriseName) {
        log.info("回调searXNG搜索，参数：{}", enterpriseName);
        SearXNGWebSearchResponse response = webSearchUtils.searXNGWebSearch(enterpriseName);
        if(response == null || CollectionUtil.isEmpty(response.getResults())) {
            return "网页搜索失败";
        }
        List<WebSearchResultDto> list = this.filterResults(response.getResults());
        if(CollectionUtil.isEmpty(list)) {
            return "网页搜索失败";
        }
        StringBuilder sb = new StringBuilder();
        for(WebSearchResultDto r: list) {
            //sb.append("网页标题：").append(r.getTitle()).append("\n");
            //sb.append("网页URL：").append(r.getUrl()).append("\n");
            sb.append("网页摘要：").append(r.getSummary()).append("\n");
            sb.append("网页内容：").append(r.getContent()).append("\n\n");
        }

        return sb.toString();
    }

    // 剔除掉百度的网页，并返回前3个可以访问的结果
    private List<WebSearchResultDto> filterResults(List<SearXNGWebSearchResponse.Results> results) {
        List<WebSearchResultDto> list = new ArrayList<>();
        if(CollectionUtil.isEmpty(results)) {
            return list;
        }
        int count = 1;
        for(SearXNGWebSearchResponse.Results r: results) {
            if(count > 3) {
                break;
            }
            count++;
            if(r.getUrl().contains("baidu.com")) {
                continue;
            }
            String webPageBodyText = webSearchUtils.getWebPageBodyText(r.getUrl());

            if(StrUtil.isEmpty(webPageBodyText)) {
                String url = r.getUrl();
                if(!url.contains("www.")) {
                    String newUrl = "";
                    if(url.contains("http://")) {
                        newUrl = "http://www." + url.substring(7);
                    }else {
                        if(url.contains("https://")) {
                             newUrl = "https://www." + url.substring(8);
                        }
                    }
                    webPageBodyText = webSearchUtils.getWebPageBodyText(newUrl);
                }
                if(StrUtil.isEmpty(webPageBodyText)) {
                    continue;
                }
            }
            WebSearchResultDto dto = new WebSearchResultDto();
            dto.setUrl(r.getUrl());
            dto.setContent(webPageBodyText);
            dto.setSummary(r.getContent());

            list.add(dto);

        }
        return list;
    }
}
